<template>
    <div class="page">
        <!-- 资金费率订单列表 -->
        <div class="card-container">
            <el-card class="box-card">
                <template #header>
                    <div class="card-header">
                        <div class="card-header-left">
                            <span class="card-title">资金费率订单列表</span>
                        </div>
                        <div class="card-header-right">
                            <el-button size="small" @click="fetchFundingOrders">
                                <span>⟲ 刷新</span>
                            </el-button>
                        </div>
                    </div>
                </template>

                <!-- 状态展示 -->
                <div v-if="fundingLoading" class="loading-container">
                    <el-skeleton :rows="5" animated />
                </div>

                <div v-else-if="fundingError" class="error-container">
                    <el-alert :title="fundingError" type="error" show-icon :closable="false" />
                    <el-button type="primary" @click="fetchFundingOrders">重试</el-button>
                </div>

                <!-- 表格 -->
                <el-table v-else v-loading="fundingLoading" :data="fundingOrdersData" style="width: 100%"
                    max-height="600" border size="default" stripe :row-class-name="getOrderRowClassName">
                    <template #empty>
                        <el-empty description="暂无数据" :image-size="80" />
                    </template>

                    <el-table-column fixed prop="symbol" label="交易对" width="170" />

                    <el-table-column prop="exchange" label="交易所" width="120" />

                    <el-table-column prop="side" label="方向" width="100" />
                    <el-table-column prop="order_type" label="订单类型" width="110">
                        <template #default="scope">
                            {{ scope.row.order_type === 'spot' ? '现货' : '合约' }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="price" label="价格" width="100" class-name="price-cell">
                        <template #default="scope">
                            <span>{{ scope.row.price.toFixed(2) }}</span>
                        </template>
                    </el-table-column>

                    <el-table-column prop="amount" label="订单数量" width="105" class-name="amount-cell" />
                    <el-table-column prop="filled" label="已成交数量" width="120" class-name="filled-cell" />
                    <el-table-column prop="remaining" label="剩余数量" width="105" class-name="filled-cell" />
                    <el-table-column prop="average_price" label="平均价格" width="105" class-name="price-cell" />
                    <el-table-column prop="fee" label="手续费" width="100" />
                    <el-table-column prop="pnl" label="盈亏" width="100" class-name="amount-cell">
                        <template #default="scope">
                            <span :class="{ 'text-positive': scope.row.pnl > 0, 'text-negative': scope.row.pnl < 0 }">
                                {{ scope.row.pnl.toFixed(2) }}
                            </span>
                        </template>
                    </el-table-column>

                    <el-table-column prop="fee" label="手续费" width="100" class-name="amount-cell">
                        <template #default="scope">
                            <span>{{ scope.row.fee.toFixed(2) }}</span>
                        </template>
                    </el-table-column>

                    <el-table-column prop="status" label="状态" width="100" class-name="status-cell">
                        <template #default="scope">
                            <span :class="getStatusClass(scope.row.status)">
                                {{ getStatusText(scope.row.status) }}
                            </span>
                        </template>
                    </el-table-column>

                    <el-table-column prop="created_at" label="创建时间" width="180">
                        <template #default="scope">
                            <el-tooltip :content="formatDateTime(scope.row.created_at)" placement="top">
                                <span class="truncate">{{ formatDateTime(scope.row.created_at) }}</span>
                            </el-tooltip>
                        </template>
                    </el-table-column>

                    <el-table-column prop="executed_at" label="执行时间" width="180">
                        <template #default="scope">
                            <el-tooltip :content="formatDateTime(scope.row.executed_at)" placement="top">
                                <span class="truncate">{{ formatDateTime(scope.row.executed_at) }}</span>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 分页 -->
                <div class="pagination-container">
                    <el-pagination v-model:current-page="fundingCurrentPage" v-model:page-size="fundingPageSize"
                        :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
                        :total="fundingOrders.total || 0" @size-change="handleFundingSizeChange"
                        @current-change="handleFundingCurrentChange" />
                </div>
            </el-card>
        </div>

        <!-- 跨交易所对冲订单列表 -->
        <div class="card-container">
            <el-card class="box-card">
                <template #header>
                    <div class="card-header">
                        <div class="card-header-left">
                            <span class="card-title">跨交易所对冲订单列表</span>
                        </div>
                        <div class="card-header-right">
                            <el-button size="small" @click="fetchSpreadOrders">
                                <span>⟲ 刷新</span>
                            </el-button>
                        </div>
                    </div>
                </template>

                <div v-if="spreadLoading" class="loading-container">
                    <el-skeleton :rows="5" animated />
                </div>

                <div v-else-if="spreadError" class="error-container">
                    <el-alert :title="spreadError" type="error" show-icon :closable="false" />
                    <el-button type="primary" @click="fetchSpreadOrders">重试</el-button>
                </div>

                <el-table v-else v-loading="spreadLoading" :data="spreadOrdersData" style="width: 100%" max-height="600"
                    border size="default" stripe :row-class-name="getOrderRowClassName">
                    <template #empty>
                        <el-empty description="暂无数据" :image-size="80" />
                    </template>

                    <el-table-column fixed prop="symbol" label="交易对" width="160" />

                    <el-table-column prop="long_exchange" label="做多" width="120" />
                    <el-table-column prop="short_exchange" label="做空" width="120" />
                    <el-table-column prop="long_price" label="做多价格" width="120" />
                    <el-table-column prop="short_price" label="做空价格" width="120" />
                    <el-table-column prop="funding_income" label="价差" width="120" />
                    <el-table-column prop="long_amount" label="做多数量" width="120" />
                    <el-table-column prop="short_amount" label="做空数量" width="120" />
                    <el-table-column prop="price_spread_pct" label="价差百分比" width="140" />
                    <el-table-column prop="position_size" label="仓位" width="140" />
                    <el-table-column prop="total_pnl" label="总盈亏" width="100">
                        <template #default="scope">
                            <span
                                :class="{ 'text-positive': scope.row.total_pnl > 0, 'text-negative': scope.row.total_pnl < 0 }">
                                {{ scope.row.total_pnl.toFixed(2) }}
                            </span>
                        </template>
                    </el-table-column>

                    <el-table-column prop="expected_profit" label="预期利润" width="120" />

                    <el-table-column prop="status" label="状态" width="100">
                        <template #default="scope">
                            <span :class="getStatusClass(scope.row.status)">
                                {{ getStatusText(scope.row.status) }}
                            </span>
                        </template>
                    </el-table-column>

                    <el-table-column prop="holding_duration" label="持有时间" width="120" />

                    <el-table-column prop="risk_level" label="风险等级" width="105">
                        <template #default="scope">
                            <span :class="getRiskLevelClass(scope.row.risk_level)">
                                {{ getRiskLevelText(scope.row.risk_level) }}
                            </span>
                        </template>
                    </el-table-column>

                    <el-table-column prop="entry_time" label="入场时间" width="180">
                        <template #default="scope">
                            <el-tooltip :content="formatDateTime(scope.row.entry_time)" placement="top">
                                <span class="truncate">{{ formatDateTime(scope.row.entry_time) }}</span>
                            </el-tooltip>
                        </template>
                    </el-table-column>

                    <el-table-column prop="exit_time" label="出场时间" width="180">
                        <template #default="scope">
                            <el-tooltip :content="formatDateTime(scope.row.exit_time)" placement="top">
                                <span class="truncate">{{ formatDateTime(scope.row.exit_time) }}</span>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                </el-table>

                <div class="pagination-container">
                    <el-pagination v-model:current-page="spreadCurrentPage" v-model:page-size="spreadPageSize"
                        :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
                        :total="spreadOrders.total || 0" @size-change="handleSpreadSizeChange"
                        @current-change="handleSpreadCurrentChange" />
                </div>
            </el-card>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { getFundingOrderList, getSpreadOrderList } from '../../services/api/Order/order';
import type { FundingOrder, SpreadOrder } from '../../services/api/Order/order';

// 资金费率订单数据
const fundingOrders = ref({
    total: 0,
    page: 1,
    page_size: 20,
    total_pages: 1,
    orders: [] as FundingOrder[]
});
const fundingLoading = ref(false);
const fundingError = ref('');
const fundingCurrentPage = ref(1);
const fundingPageSize = ref(20);

// 跨交易所对冲订单数据
const spreadOrders = ref({
    total: 0,
    page: 1,
    page_size: 20,
    total_pages: 1,
    orders: [] as SpreadOrder[]
});
const spreadLoading = ref(false);
const spreadError = ref('');
const spreadCurrentPage = ref(1);
const spreadPageSize = ref(20);

// 计算属性
const fundingOrdersData = computed(() => fundingOrders.value.orders);
const spreadOrdersData = computed(() => spreadOrders.value.orders);

// 获取资金费率订单列表
const fetchFundingOrders = async () => {
    fundingLoading.value = true;
    fundingError.value = '';

    try {
        const response = await getFundingOrderList({
            page: fundingCurrentPage.value,
            page_size: fundingPageSize.value,
            execution_mode: "live"
        });
        if ('data' in response) {
            fundingOrders.value = response.data;
        } else {
            fundingOrders.value = response;
        }

        fundingError.value = '';
    } catch (error: any) {
        console.error('获取资金费率订单列表异常:', error);
        fundingError.value = error.message || '获取数据失败，请稍后重试';
    } finally {
        fundingLoading.value = false;
    }
};

// 获取跨交易所对冲订单列表
const fetchSpreadOrders = async () => {
    spreadLoading.value = true;
    spreadError.value = '';

    try {
        const response = await getSpreadOrderList({
            page: spreadCurrentPage.value,
            page_size: spreadPageSize.value,
            is_simulation: true
        });
        if ('data' in response) {
            spreadOrders.value = response.data;
        } else {
            spreadOrders.value = response;
        }
        spreadError.value = '';
    } catch (error: any) {
        console.error('获取跨交易所对冲订单列表异常:', error);
        spreadError.value = error.message || '获取数据失败，请稍后重试';
    } finally {
        spreadLoading.value = false;
    }
};

// 分页处理
const handleFundingSizeChange = (size: number) => {
    fundingPageSize.value = size;
    fetchFundingOrders();
};

const handleFundingCurrentChange = (current: number) => {
    fundingCurrentPage.value = current;
    fetchFundingOrders();
};

const handleSpreadSizeChange = (size: number) => {
    spreadPageSize.value = size;
    fetchSpreadOrders();
};

const handleSpreadCurrentChange = (current: number) => {
    spreadCurrentPage.value = current;
    fetchSpreadOrders();
};

// 辅助函数
const formatDateTime = (dateString: string) => {
    if (!dateString) return '-';
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
};

const getStatusClass = (status: string) => {
    switch (status) {
        case 'open':
            return 'status-open';
        case 'closed':
            return 'status-closed';
        case 'partially_filled':
        case 'partial':
            return 'status-partial';
        case 'canceled':
            return 'status-canceled';
        case 'rejected':
        case 'failed':
            return 'status-failed';
        default:
            return '';
    }
};

const getStatusText = (status: string) => {
    const statusMap: Record<string, string> = {
        'open': '进行中',
        'closed': '完成',
        'partially_filled': '部分成交',
        'partial': '部分成交',
        'canceled': '已取消',
        'rejected': '失败',
        'failed': '失败'
    };
    return statusMap[status] || status;
};

const getRiskLevelClass = (level: string) => {
    switch (level) {
        case 'low':
            return 'risk-low';
        case 'medium':
            return 'risk-medium';
        case 'high':
            return 'risk-high';
        default:
            return '';
    }
};

const getRiskLevelText = (level: string) => {
    const riskMap: Record<string, string> = {
        'low': '低',
        'medium': '中',
        'high': '高'
    };
    return riskMap[level] || level;
};

// 获取订单行样式
const getOrderRowClassName = ({ row }: { row: FundingOrder | SpreadOrder }) => {
    if (row.status === 'closed') return 'success-row';
    if (row.status === 'failed' || row.status === 'rejected') return 'danger-row';
    if (row.status === 'partially_filled' || row.status === 'partial') return 'warning-row';
    if (row.status === 'open') return 'info-row';
    return '';
};

// 组件挂载时加载数据
onMounted(() => {
    fetchFundingOrders();
    fetchSpreadOrders();
});
</script>

<style scoped>
.page {
    background-color: #f5f7fa;
    min-height: 100vh;
    padding: 16px;
}

.card-container {
    width: 100%;
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.card-container {
    margin-bottom: 24px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    border-radius: 8px;
    overflow: hidden;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.card-header-left {
    display: flex;
    align-items: center;
}

.card-title {
    font-size: 18px;
    font-weight: 600;
    color: #1890ff;
}

.loading-container,
.error-container {
    padding: 16px;
}

.error-container {
    display: flex;
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
}

.pagination-container {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
    padding-right: 8px;
}

.mono {
    font-family: 'Segoe UI', 'Roboto', 'Helvetica Neue', Arial, sans-serif;
    font-weight: 500;
    color: #262626;
    font-size: 14px;
}

.muted {
    color: #6b7280;
}

.truncate {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    display: inline-block;
    max-width: 100%;
}

/* 表格样式 */
:deep(.el-table) {
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
    width: 100%;
    display: block;
    overflow-x: auto;
}

:deep(.el-table th) {
    background-color: #fafafa !important;
    color: #262626 !important;
    font-weight: 600 !important;
    font-size: 14px;
    border-bottom: 2px solid #e8e8e8;
    height: 48px;
    padding: 0 12px;
}

:deep(.el-table tr) {
    height: 48px;
    transition: background-color 0.2s ease;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
    background-color: transparent !important;
}

:deep(.el-table__body tr:nth-child(odd)) {
    background-color: #FCFCFC !important;
}

:deep(.el-table__body tr:nth-child(even)) {
    background-color: #FFFFFF !important;
}

:deep(.el-table__body tr:hover > td) {
    background-color: #f0f7ff !important;
}

:deep(.el-table .el-table__fixed-right .cell) {
    background: #fff;
}

:deep(.el-table) {
    width: 100%;
    display: block;
    overflow-x: auto;
}

.status-open {
    padding: 4px 8px;
    border-radius: 4px;
    background-color: #e6f7ff;
    color: #1890ff;
    font-size: 12px;
    font-weight: 500;
}

.status-closed {
    padding: 4px 8px;
    border-radius: 4px;
    background-color: #f6ffed;
    color: #52c41a;
    font-size: 12px;
    font-weight: 500;
}

.status-partial {
    padding: 4px 8px;
    border-radius: 4px;
    background-color: #fff7e6;
    color: #fa8c16;
    font-size: 12px;
    font-weight: 500;
}

.status-canceled {
    padding: 4px 8px;
    border-radius: 4px;
    background-color: #f5f5f5;
    color: #8c8c8c;
    font-size: 12px;
    font-weight: 500;
}

.status-failed {
    padding: 4px 8px;
    border-radius: 4px;
    background-color: #fff2f0;
    color: #ff4d4f;
    font-size: 12px;
    font-weight: 500;
}

.risk-low {
    color: #52c41a !important;
    font-weight: 600;
}

.risk-medium {
    color: #faad14 !important;
    font-weight: 600;
}

.risk-high {
    color: #ff4d4f !important;
    font-weight: 600;
}

:deep(.success-row) {
    background-color: #f6ffed;
}

:deep(.warning-row) {
    background-color: #fffbe6;
}

:deep(.danger-row) {
    background-color: #fff2f0;
}

:deep(.info-row) {
    background-color: #e6f7ff;
}

:deep(.success-row:hover>td) {
    background-color: #e6f7ff !important;
}

:deep(.warning-row:hover>td) {
    background-color: #fff1b8 !important;
}

:deep(.danger-row:hover>td) {
    background-color: #ffccc7 !important;
}

:deep(.info-row:hover>td) {
    background-color: #bae7ff !important;
}

:deep(.el-table__body tr td:first-child) {
    color: #000000 !important;
    font-weight: 500;
}

:deep(.el-table__body tr td:nth-child(2)) {
    color: #000000 !important;
    font-weight: 400;
}

:deep(.text-positive) {
    color: #52c41a !important;
    font-weight: 500;
}

:deep(.text-negative) {
    color: #ff4d4f !important;
    font-weight: 500;
}

.loading-container,
.error-container {
    padding: 16px;
}

.error-container {
    display: flex;
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
}

.box-card {
    border-radius: 10px;
    box-shadow: 0 6px 18px rgba(15, 23, 42, 0.06);
    padding: 12px;
    background: #fff;
}

:deep(.el-table__body td.price-cell,
    .el-table__body td.amount-cell,
    .el-table__body td.filled-cell,
    .el-table__body td.status-cell) {
    font-weight: 500;
    font-size: 14px;
}

:deep(.success-cell) {
    background-color: #f6ffed;
    border-color: #b7eb8f;
}

:deep(.warning-cell) {
    background-color: #fffbe6;
    border-color: #ffe58f;
}

:deep(.danger-cell) {
    background-color: #fff2f0;
    border-color: #ffccc7;
}

:deep(.el-table__header th) {
    background-color: #fafafa !important;
    font-weight: 600 !important;
}

@media screen and (max-width: 768px) {
    .hide-sm {
        display: none;
    }

    .page {
        padding: 10px;
    }

    .card-title {
        font-size: 16px;
    }
}
</style>